/**
 * 账号服务模块
 * 负责管理用户账号信息的数据库操作
 */
import * as sqlite3 from 'sqlite3';
import * as path from 'path';
import * as fs from 'fs';

interface Account {
  id: string;
  platformId: string;
  username: string;
  token: string;
  refreshToken?: string;
  expiresAt?: Date;
  isActive: boolean;
  createdAt: Date;
}

export class AccountService {
  private db: sqlite3.Database;

  constructor() {
    try {
      // 确保数据库目录存在
      const dataDir = path.join(__dirname, '../../../data');
      if (!fs.existsSync(dataDir)) {
        fs.mkdirSync(dataDir, { recursive: true });
        console.log('数据库目录已创建:', dataDir);
      }
      
      const dbPath = path.join(dataDir, 'app.db');
      console.log('正在连接数据库:', dbPath);
      
      this.db = new sqlite3.Database(dbPath, (err) => {
        if (err) {
          console.error('数据库连接失败:', err.message);
          throw err;
        } else {
          console.log('数据库连接成功');
        }
      });
      
      this.initDatabase();
    } catch (error) {
      console.error('AccountService 初始化失败:', error);
      throw error;
    }
  }

  /**
   * 初始化数据库表结构
   */
  private initDatabase() {
    this.db.run(`
      CREATE TABLE IF NOT EXISTS accounts (
        id TEXT PRIMARY KEY,
        platformId TEXT NOT NULL,
        username TEXT NOT NULL,
        token TEXT NOT NULL,
        refreshToken TEXT,
        expiresAt DATETIME,
        isActive BOOLEAN DEFAULT 1,
        createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (platformId) REFERENCES platforms (id)
      )
    `, (err) => {
      if (err) {
        console.error('创建accounts表失败:', err.message);
      } else {
        console.log('accounts表初始化成功');
      }
    });
  }

  /**
   * 获取所有活跃账号
   */
  async getAccounts(): Promise<Account[]> {
    return new Promise((resolve, reject) => {
      this.db.all('SELECT * FROM accounts WHERE isActive = 1', (err, rows) => {
        if (err) {
          console.error('获取账号列表失败:', err.message);
          reject(err);
        } else {
          console.log(`成功获取 ${rows.length} 个账号`);
          resolve(rows as Account[]);
        }
      });
    });
  }

  /**
   * 添加新账号
   */
  async addAccount(account: Omit<Account, 'id' | 'createdAt'>): Promise<string> {
    const id = this.generateId();
    return new Promise((resolve, reject) => {
      this.db.run(
        'INSERT INTO accounts (id, platformId, username, token, refreshToken, expiresAt, isActive) VALUES (?, ?, ?, ?, ?, ?, ?)',
        [id, account.platformId, account.username, account.token, account.refreshToken, account.expiresAt, account.isActive],
        (err) => {
          if (err) {
            console.error('添加账号失败:', err.message);
            reject(err);
          } else {
            console.log(`成功添加账号: ${account.username} (${account.platformId})`);
            resolve(id);
          }
        }
      );
    });
  }

  /**
   * 删除账号（软删除）
   */
  async removeAccount(accountId: string): Promise<void> {
    return new Promise((resolve, reject) => {
      this.db.run('UPDATE accounts SET isActive = 0 WHERE id = ?', [accountId], (err) => {
        if (err) {
          console.error('删除账号失败:', err.message);
          reject(err);
        } else {
          console.log(`成功删除账号: ${accountId}`);
          resolve();
        }
      });
    });
  }

  /**
   * 根据平台获取账号
   */
  async getAccountByPlatform(platformId: string): Promise<Account | null> {
    return new Promise((resolve, reject) => {
      this.db.get(
        'SELECT * FROM accounts WHERE platformId = ? AND isActive = 1 ORDER BY createdAt DESC LIMIT 1',
        [platformId],
        (err, row) => {
          if (err) {
            console.error('获取平台账号失败:', err.message);
            reject(err);
          } else {
            console.log(`获取平台 ${platformId} 账号:`, row ? '成功' : '未找到');
            resolve(row as Account || null);
          }
        }
      );
    });
  }

  /**
   * 更新账号token
   */
  async updateToken(accountId: string, token: string, refreshToken?: string, expiresAt?: Date): Promise<void> {
    return new Promise((resolve, reject) => {
      this.db.run(
        'UPDATE accounts SET token = ?, refreshToken = ?, expiresAt = ? WHERE id = ?',
        [token, refreshToken, expiresAt, accountId],
        (err) => {
          if (err) {
            console.error('更新账号token失败:', err.message);
            reject(err);
          } else {
            console.log(`成功更新账号token: ${accountId}`);
            resolve();
          }
        }
      );
    });
  }

  /**
   * 生成唯一ID
   */
  private generateId(): string {
    return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
  }
}
